<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>即时通讯</title>
<script src="/js/jquery-2.1.1.min.js"></script>
<script src="/js/sockjs.min.js"></script>
</head>
<body>
    <h2>即时通讯</h2>
    	发送人ID：<input type="text" id="token" placeholder="输入token"/>
    <br/>
    	接收人ID：<input type="text" id="receiver" placeholder="输入接收人id"/>
     <br/>
     <input id="tokenBut" value="创建连接" type="button">
     <br/>
    <textarea rows="4" cols="60" name="text" id="content"></textarea><br/>
    <input type="submit" value="发送" id="send"/>
    <br/>
    <input type="button" value="断开连接" id="stop" />
    <input style="margin-left:20px;" type="button" value="clear" id="clear" />
    <ul id="response"></ul>
    <ul id="patients"></ul>

<script>

    //创建socket
    var websocket;
    var timer;
    
    var title = $('title').text();
    $('body').on('click', function() {
        clearInterval(timer);
        $('title').text(title);
    });
    
    function createWebsocket() {
        var token = $('#token').val();
        var receiverId = $("#receiver").val();
		if ('WebSocket' in window) {
            websocket = new WebSocket("ws://192.168.1.107:9998/ws?token="+token+"&to="+receiverId);
        } else if ('MozWebSocket' in window) {
			websocket = new MozWebSocket("ws://192.168.1.107:9998/ws?token="+token+"&to="+receiverId);
		} else {
			websocket = new SockJS("http://192.168.1.107:9998/ws?token="+token+"&to="+receiverId);
		}

        websocket.onopen = function(event) {
            console.log("WebSocket:已连接");
        };

        //来消息了
        websocket.onmessage = function(ev) {
            var obj=JSON.parse(ev.data);
            if(!obj || obj == undefined) {
                return false;
            }

            var cur = obj.from;
            if(!!obj.message) {//如果空消息不予处理
            	var index = 0;
                timer = setInterval(function() {
                	var mess = "【新消息】"+obj.message;
                    if(index%2) {
                    	mess = "【　　　】"+obj.message;
                    }
                    parent.document.title=mess;//报错：Uncaught DOMException: Blocked a frame with origin "http://192.168.1.107:7072" from accessing a cross-origin frame.
                    index++;
                }, 500);
                $("#response").append("<li>回复:" + obj.message + "</li>");
            }else if(!!obj.from){
                $("#patients").append("<li>上线:" + obj.from + "</li>");
            }
        };

        websocket.onerror = function(event) {
            console.log("WebSocket:发生错误 ");
        };

        websocket.onclose = function(event) {
            console.log("WebSocket:已关闭");
        }
    }

    function notifyMe(newMessage) {
        // 先检查浏览器是否支持
        if (!("Notification" in window)) {
            alert("This browser does not support desktop notification");
        }

        // 检查用户是否同意接受通知
        else if (Notification.permission === "granted") {
            // If it's okay let's create a notification
            var notification = new Notification('患者张三发起咨询',{body:newMessage});
            notification.onclick = function() {//单击消息提示框，进入浏览器页面
                window.focus();
            }
        }

        // 否则我们需要向用户获取权限
        else if (Notification.permission !== 'denied') {
            Notification.requestPermission(function (permission) {
                // 如果用户同意，就可以向他们发送通知
                if (permission === "granted") {
                    var notification = new Notification('患者张三发起咨询',{body:newMessage});
                }
                notification.onclick = function() {//单击消息提示框，进入浏览器页面
                    window.focus();
                }
            });
        }

    }


    //发送事件
    $("#send").click(function(e) {
        var val = $("#content").val();
        var receiverId = $("#receiver").val();
        e.preventDefault();
        showLocal(val);
        send(val,receiverId);
    });
    function showLocal(message) {
        $("#response").append("<li>Local:" + message + "</li>");
    }
    $("#stop").click(function() {
        console.log('====websocket:' + websocket);
        websocket.close();
        console.log('====websocket:' + websocket);
    });
    $("#clear").click(function() {
        $("#response li").remove();
        $("#patients li").remove();
    });

    //发送事件执行方法
    function send(val,receiverId) {
        if(val != null && val != '') {
            var param = {
                curPatientId:receiverId,
                text:val
            }
            this.websocket.send(JSON.stringify(param));
        }else {
            alert("不能发送空值");
        }
    }

    document.onkeydown = function(a) {
        var b = document.all ? window.event: a;
        return 13 == b.keyCode ? (send(), !1) : void 0
    };

    $("#tokenBut").click(function(){
        createWebsocket();
    });

    </script>
</body>
</html>